<?php

namespace tmcore\services\addons;

use app\common\enum\ChannelEnum;
use app\common\model\setting\Config as ConfigModel;
use tmcore\exceptions\AddonsException;
use tmcore\services\ConfigService;
use tmcore\services\HttpService;
use tmcore\traits\ErrorTrait;
use tmcore\traits\TransTrait;
use think\facade\Request;
use Exception;

/**
 * 平台接口调用
 */
class AddonApiService
{
    use ErrorTrait;
    use TransTrait;

    //接口网址
    const PORT_ROOT = "https://api.tmadmin.cn/channel/";

    /**
     * 错误信息
     * @var string
     */
    private static $curlError;

    /**
     * header头信息
     * @var string
     */
    private static $curlHeader;

    /**
     * 返回信息
     * @var array
     */
    private static $curlContent;

    /**
     * 请求信息
     * @var array
     */
    private static $curlInfo;

    /**
     * 获取当前域名
     */
    public static function getDomain() {
        return Request::domain();
    }

    /**
     * 获取授权配置
     * @param string $type get-获取 create-更新 set-设置
     * @param string $key 项目key值
     * @param array $data 更新数据
     * @return array
     */
    public static function getAuthConfig($type = 'get', $key = '', $data = [])
    {
        if($type == 'set') {
            $value = (new ConfigModel)->where(['name' => 'auth'])->value('value');
            $settings = json_decode($value, true);

            //更新授权信息
            if(isset($data['project_name']))$settings['project_name'] = $data['project_name'];
            if(isset($data['project_identify']))$settings['project_identify'] = $data['project_identify'];
            if(isset($data['project_type']))$settings['project_type'] = $data['project_type'];
            if(isset($data['account']))$settings['account'] = $data['account'];
            if(isset($data['password']))$settings['password'] = $data['password'];
            if(isset($data['user_token']))$settings['user_token'] = $data['user_token'];
            if(isset($data['expire_time']))$settings['expire_time'] = $data['expire_time'];
            if(isset($data['is_login']))$settings['is_login'] = $data['is_login'];

            (new ConfigModel)->where(['name' => 'auth'])->update(['value' => json_encode($settings, 320)]);
            (new ConfigService)->setConfig('create', 'sys', 'auth');
            return $settings;
        } else {
            //检验授权配置
            $config = (new ConfigService)->setConfig($type, 'sys', 'auth');
            if($config) {
                return $key?$config[$key]:$config;
            } else {
                return [];
            }
        }
    }

    /**
     * 获取授权user_token
     * @param array $params 参数
     * @param bool $is_refresh 获取形式 true-强制刷新 false-默认获取
     * @return mixed
     * @throws AddonsException
     */
    public static function user_token($params = [], $is_refresh = false)
    {
        try{
            $auth_config = self::getAuthConfig('get');
            if(!$auth_config) throw new Exception('授权配置信息不存在');

            //避免user_token临界问题 延时10秒
            if (!$is_refresh && isset($auth_config['expire_time']) && ((int)$auth_config['expire_time']-10) > time()) {
                return $auth_config['user_token'];
            }

            $account = $params['account'] ?? $auth_config['account'];
            $password = $params['password'] ?? $auth_config['password'];

            if(!$is_refresh && (!$account || !$password)) return $auth_config['user_token'];

            $url = self::PORT_ROOT.'login';
            $data = [
                'account' => $account,
                'password' => $password,
                'channel' => ChannelEnum::PC,
                'login_type' => 1,
            ];

            //接口调用
            $http = HttpService::postRequest($url, $data);
            $result = json_decode($http,true);
            self::checkApiResult($result, '获取授权user_token失败');

            //更新授权信息
            self::getAuthConfig('set', [], [
                'account' => $data['account'],
                'password' => $data['password'],
                'user_token' => $result['data']['token'],
                'expire_time' => $result['data']['expire_time'],
                'is_login' => 1,
            ]);

            return $result['data']['token'];
        } catch (Exception $e) {
            throw new AddonsException($e->getMessage());
        }
    }

    /**
     * 用户退出
     * @return bool
     * @throws AddonsException
     */
    public static function user_logout()
    {
        try{
            $auth_config = self::getAuthConfig('get');
            if(!$auth_config) throw new Exception('授权配置信息不存在');

            //更新授权信息
            self::getAuthConfig('set', [], [
                'account' => '',
                'password' => '',
                'user_token' => '',
                'expire_time' => 3600,
                'is_login' => 0,
            ]);

            return true;
        } catch (Exception $e) {
            throw new AddonsException($e->getMessage());
        }
    }

    /**
     * 获取插件信息列表
     * @return array
     * @throws AddonsException
     */
    public static function get_addons_list($params = [])
    {
        try {
            $info = self::getAuthConfig();
            if(!$info) throw new Exception("获取不到项目信息");

            $user_token = self::user_token();

            $url = self::PORT_ROOT.'plugin/lists';
            $data = [
                'project_identify' => $info['project_identify'],
                'project_type' => $info['project_type'],
            ];
            if(!empty($params['name'])) $data['name'] = $params['name'];
            if(!empty($params['category_id'])) $data['category_id'] = $params['category_id'];

            //接口调用
            $http = HttpService::getRequest($url, $data, ['Authorization: ' . $user_token]);
            $result = json_decode($http,true);
            self::checkApiResult($result, '获取插件信息列表失败');

            return $result['data'];
        } catch (Exception $e) {
            throw new AddonsException($e->getMessage());
        }
    }

    /**
     * 获取插件分类列表
     * @return array
     * @throws AddonsException
     */
    public static function get_addons_category_list($params = [])
    {
        try {
            $info = self::getAuthConfig();
            if(!$info) throw new Exception("获取不到项目信息");

            $user_token = self::user_token();

            $url = self::PORT_ROOT.'plugin/categoryLists';
            $data = [
                'project_identify' => $info['project_identify'],
                'project_type' => $info['project_type'],
            ];
            if(!empty($params['name'])) $data['name'] = $params['name'];

            //接口调用
            $http = HttpService::getRequest($url, $data, ['Authorization: ' . $user_token]);
            $result = json_decode($http,true);
            self::checkApiResult($result, '获取插件分类列表失败');

            return $result['data'];
        } catch (Exception $e) {
            throw new AddonsException($e->getMessage());
        }
    }

    /**
     * 获取插件信息
     * @param string $identify
     * @return array
     * @throws AddonsException
     */
    public static function get_addons_info($identify)
    {
        try {
            $info = self::getAuthConfig();
            if(!$info) throw new Exception("获取不到项目信息");

            $user_token = self::user_token();

            $url = self::PORT_ROOT.'plugin/detail';
            $data = [
                'identify'=> $identify,
                'project_identify' => $info['project_identify'],
                'project_type' => $info['project_type'],
            ];

            //接口调用
            $http = HttpService::getRequest($url, $data,['Authorization: ' . $user_token]);
            $result = json_decode($http,true);
            self::checkApiResult($result, '获取插件信息失败');

            return $result['data'];
        } catch (Exception $e) {
            throw new AddonsException($e->getMessage());
        }
    }

    /**
     * 插件版本包下载
     * @param $identify
     * @param string $version 版本号
     * @param string $save_path 保存路径
     * @return bool
     * @throws AddonsException
     */
    public static function addons_version_download($identify, $version, $save_path)
    {
        try {
            $info = self::getAuthConfig();
            if(!$info) throw new Exception("获取不到项目信息");

            $user_token = self::user_token();

            $url = self::PORT_ROOT.'plugin/download';
            $data = [
                'identify'=> $identify,
                'version'=> $version,
                'project_identify' => $info['project_identify'],
                'project_type' => $info['project_type'],
            ];

            //接口调用
            $http = HttpService::postRequest($url, $data,['Authorization: ' . $user_token], 10 , false, true);
            $result = json_decode($http, true);
            if($result) {
                self::checkApiResult($result, '插件版本包下载失败');
            } else {
                $result = $http;
            }

            //检查目录
            if(!file_exists($save_path)) mkdir($save_path,0755,true);
            //下载文件
            $res = file_put_contents($save_path . '/' . $version . '.zip', $result);
            if($res) {
                return true;
            } else {
                throw new Exception("下载插件版本包失败");
            }
        } catch (Exception $e) {
            throw new AddonsException($e->getMessage());
        }
    }

    /**
     * 检查接口返回值
     * @param $data
     * @param string $msg
     * @return void
     * @throws Exception
     */
    private static function checkApiResult($data, $msg = '接口错误')
    {
        if(!$data) {
            $curl_error = HttpService::getRequestError();
            if($curl_error) {
                throw new Exception($curl_error);
            } else {
                throw new Exception('接口网络错误');
            }
        } else {
            if(isset($data['code']) && $data['code'] != 0) throw new Exception($data['msg'] ?? $msg);
        }
    }
}